package cn.zhx.xa.system.utils;

import cn.zhx.xa.model.vo.common.ResultCodeEnum;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

@Service
@Slf4j
public class LockService {

    @Resource
    private RedissonClient redissonClient;

    public <T> T executeWithLock(String key, int waitTime, TimeUnit unit, Supplier<T> supplier){
        RLock lock = redissonClient.getLock(key);
        boolean lockSuccess = false;
        try {
            lockSuccess = lock.tryLock(waitTime, unit);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        if (!lockSuccess) {
            throw new RuntimeException(String.valueOf(ResultCodeEnum.LOCK_LIMIT));
        }
        try {
            return supplier.get();//执行锁内的代码逻辑
        } finally {
            lock.unlock();
        }
    }
}